package com.danco.training.controller;



import java.io.FileWriter;
import java.io.IOException;
import java.io.Serializable;
import java.util.Date;

import com.danco.training.bookshop.entity.Book;
import com.danco.training.bookshop.entity.Claim;
import com.danco.training.bookshop.entity.Order;
import com.danco.training.bookshop.entity.storage.Bookshop;
import com.danco.training.bookshop.entity.storage.OrderStorage;
import com.danco.training.bookshop.service.file.BookStorageFile;
import com.danco.training.bookshop.service.file.OrderStorageFile;
import com.danco.training.bookshop.service.storage.BookStorageService;
import com.danco.training.bookshop.service.storage.OrderStorageService;
import com.danco.training.csvworker.CSVReader;
import com.danco.training.view.IOUtil;
import com.danco.training.view.Separator;

public class OrderController implements Serializable{
	

	/**
	 * 
	 */
	private static final long serialVersionUID = -9033349643981321595L;
	private OrderStorageService orderStorageService = Bookshop.getBookshopInstance().getOrderStorageService();
	private BookStorageService bookStorageService = Bookshop.getBookshopInstance().getBookStorageService();
	
	private BookController bookController = new BookController();

	public void printOrderList() {
		IOUtil.write("Orders in OrderStorage");
		for(Order order:orderStorageService.getOrderList()){
		IOUtil.write(orderDetails(order.getId()));
		}
		
	}

	public void printOrderListSortedByOrderDate() {
		IOUtil.write("Orders in OrderStorage sorted by execution date");
		for(Order order:orderStorageService.sortOrdersByOrderDate(orderStorageService.getOrderList())){
			IOUtil.write(orderDetails(order.getId()));
			}
		
	}

	public void printExecutedOrders() {
		IOUtil.write("Executed Orders in OrderStorage ");
		for(Order order:orderStorageService.getExecutedOrders(orderStorageService.getOrderList())){
			IOUtil.write(orderDetails(order.getId()));
			}
		

	}

	public void printNotExecutedOrders() {
		IOUtil.write("Not Executed Orders in OrderStorage ");
		for(Order order:orderStorageService.getNotExecutedOrders(orderStorageService.getOrderList())){
			IOUtil.write(orderDetails(order.getId()));
			}
		
	}

	public void printExecutedOrderListSortedByOrderDate() {
		IOUtil.write("Enter date  from ");
		
		Date d1 = IOUtil.readDate();
		IOUtil.write("Enter date day to");
		
		Date d2 = IOUtil.readDate();
		IOUtil.write("Executed Orders in OrderStorage sorted by execution date ");
		for(Order order:orderStorageService.sortExecutedOrdersByOrderDate(orderStorageService.getOrderList(),d1,d2)){
			IOUtil.write(orderDetails(order.getId()));
			}
		

	}

	public void printExecutedOrderListSortedByPrice() {
IOUtil.write("Enter date  from ");
		
		Date d1 = IOUtil.readDate();
		IOUtil.write("Enter date day to");
		
		Date d2 = IOUtil.readDate();
		IOUtil.write("Executed Orders in OrderStorage sorted by price ");
		for(Order order:orderStorageService.sortExecutedOrdersByPrice(orderStorageService.getOrderList(),d1,d2)){
			IOUtil.write(orderDetails(order.getId()));
			}
	}

	public void createOrder() {
		IOUtil.write("Order creation");
		
		Order order = new Order(orderStorageService.generateUnexistedId());
		orderStorageService.addOrder(order);
		IOUtil.write("Enter book Id to add:");
		bookController.printBookList();
		int bookId = IOUtil.readInt();
		
		orderStorageService.addBookToOrder(order,bookStorageService.getBookById(bookId));
		IOUtil.write("Order is created");
		IOUtil.write(orderDetails(order.getId()));
		

	}
	
	public String orderDetails(int index) {

		Order i = orderStorageService.getOrderById(index);
		StringBuffer str = new StringBuffer(i.getId() + Separator.SEPARATOR.getS());
		for (Book book : i.getBooks()) {
			str.append(book.getId());
			str.append(Separator.BOOK_SEPARATOR_IN_ORDER.getS());

		}
		str.append(Separator.SEPARATOR.getS());
		str.append(i.isExecuted()+ Separator.SEPARATOR.getS());
		str.append(i.getTotalPrice());
		return str.toString();

	}

	public void printOrderInfo() {
		IOUtil.write("Enter order Id:");
		int id = IOUtil.readInt();
		while (orderStorageService.getOrderById(id)== null){
			IOUtil.write("Order not existed");
			IOUtil.write("Enter order's to show Id");
			id = IOUtil.readInt();
		}
		IOUtil.write(orderDetails(id));
	}

	public void updateOrder(){
		IOUtil.write("Enter order Id for modifying");
		int id = IOUtil.readInt(); 
		while (orderStorageService.getOrderById(id)== null){
			IOUtil.write("Order not existed");
			IOUtil.write("Enter order's Id");
			id = IOUtil.readInt();
		}
		Order order = orderStorageService.getOrderById(id);
		
		IOUtil.write("Change order state : y/n");
		if (!IOUtil.read().equals("y") ){
			order.setExecuted(!order.isExecuted());
		}
		IOUtil.write(orderDetails(id));
		

	}

	public void deleteOrder() {
		IOUtil.write("Enter order Id");
		int id = IOUtil.readInt();
		while (orderStorageService.getOrderById(id)== null){
			IOUtil.write("Order not existed");
			IOUtil.write("Enter order's to show Id");
			id = IOUtil.readInt();
		}
		orderStorageService.rejectOrder(id);

	}

	public void addBookToOrder() {
		IOUtil.write("Enter order Id for modifying");
		int id = IOUtil.readInt(); 
		while (orderStorageService.getOrderById(id)== null){
			IOUtil.write("Order not existed");
			IOUtil.write("Enter order's to show Id");
			id = IOUtil.readInt();
		}
		Order order = orderStorageService.getOrderById(id);
		
		IOUtil.write("Enter book id to add");
		bookController.printBookList();
		int bookId = IOUtil.readInt(); 
		while (bookStorageService.getBookById(bookId)== null){
		
			IOUtil.write("Enter book's to show Id");
			
			bookId = IOUtil.readInt();
		}
		orderStorageService.addBookToOrder(order, bookStorageService.getBookById(bookId));

	}

	public void deleteBookFromOrder() {
		IOUtil.write("Enter order Id for modifying");
		int id = IOUtil.readInt(); 
		while (orderStorageService.getOrderById(id)== null){
			IOUtil.write("Order not existed");
			IOUtil.write("Enter order's to show Id");
			id = IOUtil.readInt();
		}
		Order order = orderStorageService.getOrderById(id);
		
		IOUtil.write("Enter book id to delete");
		int bookId = IOUtil.readInt(); 
		while (bookStorageService.getBookById(bookId)== null){
			IOUtil.write("Book not existed");
			IOUtil.write("Enter book's to show Id");
			
			bookId = IOUtil.readInt();
		}
		orderStorageService.removeBookFromOrder(order, bookStorageService.getBookById(bookId));
		IOUtil.write("Book is deleted from order");
		IOUtil.write(orderDetails(id));

	}

	public void executeOrder() {
		IOUtil.write("Enter order Id for modifying");
		int id = IOUtil.readInt(); 
		while (orderStorageService.getOrderById(id)== null){
			IOUtil.write("Order not existed");
			IOUtil.write("Enter order's to show Id");
			id = IOUtil.readInt();
		}
		orderStorageService.executeOrderById(id);
	}

	public void copyOrder()  {
		IOUtil.write("Enter order Id to copy");
		int id = IOUtil.readInt(); 
		
		while (orderStorageService.getOrderById(id) == null){
			IOUtil.write("Order to copy not existed");
			IOUtil.write("Enter order's to copy Id");
			id = IOUtil.readInt();
		}

		try {
			Order copy = orderStorageService.createOrderCopy(orderStorageService.getOrderById(id));
		
	
		IOUtil.write("Order is created");
		IOUtil.write(orderDetails(copy.getId()));
		} catch (CloneNotSupportedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void saveOrderListToFile() throws IOException {
		 IOUtil.write("Enter directory and file name for saving");
			String file = IOUtil.read();
			if (file.isEmpty()){
				file = "d:\\file1.csv";
				IOUtil.write("Saved by default in d:\\file1.csv ");
				
			}
				try
				{
				FileWriter writer = new FileWriter(file, false);
				for(int id: orderStorageService.getOrderListId()){
					if(CSVReader.existedEntity(file, id)){
						writer.append('\n');
					}
					else{
					writer.append(orderDetails(id));
					writer.append('\n');
				}
				}
			     writer.close();
			    }
			    catch(IOException e)
			    {
			         e.printStackTrace();
			    }
				
	}
	
	public void readOrderListFromFile() throws IOException {
		 IOUtil.write("Enter directory and file name ");
			String file = IOUtil.read();
			if (file.isEmpty()){
				file = "d:\\file1.csv";
					
			}
			for (int i = 0; i < CSVReader.readFile(file).length; i++) {
				String order[] = CSVReader.readFile(file)[i].split(Separator.SEPARATOR.getS());
				Order or = new Order(Integer.parseInt(order[0]));
				orderStorageService.addOrder(or);
				String books[] = order[1].split(Separator.BOOK_SEPARATOR_IN_ORDER.getS());
					for (int j = 0; j < books.length-1; j++){
						orderStorageService.addBookToOrder(or, bookStorageService.getBookById(Integer.parseInt(books[j])));
				}
					or.setExecuted(Boolean.parseBoolean(order[2]));
					or.setTotalPrice(Double.parseDouble(order[3]));
					orderStorageService.addOrder(or);//must be updateOrder
			    
			}
	}
	
}
